package com.xyh.transaction.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.xyh.transaction.excel.ExcelCellWidthStyleStrategy;
import com.xyh.transaction.excel.FixedRowHeightHandler;
import com.xyh.transaction.excel.StyleUtils;
import com.xyh.transaction.exception.ExcelExportException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.List;

public class ExcelUtil {

    public static ResponseEntity<byte[]> exportToExcel(
            List<?> excelDataList,
            String fileName, Class<?> clazz) {
        try {
            // 设置单元格样式
            HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                    new HorizontalCellStyleStrategy(StyleUtils.getHeadStyle(), StyleUtils.getContentStyle());

            // 列宽策略设置
            ExcelCellWidthStyleStrategy widthStyleStrategy = new ExcelCellWidthStyleStrategy();

            // 使用 EasyExcel 写入 Excel 数据到 outputStream
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ExcelWriterBuilder excelWriterBuilder = EasyExcel.write(outputStream,clazz);
            excelWriterBuilder
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(widthStyleStrategy)
                    .registerWriteHandler(new FixedRowHeightHandler(20))
                    .sheet()
                    .doWrite(excelDataList);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);

            return ResponseEntity
                    .status(HttpStatus.OK)
                    .headers(headers)
                    .body(outputStream.toByteArray());
        } catch (Exception e) {
            // 处理异常情况，可以将异常信息返回给前端
            throw new ExcelExportException(e.getMessage() == null ? e.toString() : e.getMessage());
        }
    }

    public static void readExcel(InputStream file, Class<?> clazz, ReadListener<?> readListener) {
        EasyExcel
                .read(file, clazz, readListener)
                .sheet()
                .doRead();
    }
}
